<template>
    <view class="content">
		<!-- 弹出抽屉 -->
		<u-popup v-model="show" :length="750" mode="left">
			<!-- 背景图 -->
			<view class="popup-bgimg">
				<image class="popup-bgimg" :src="_user_info.pictureBanner":style="{ width: '100%', height: '100%','z-index': '-1' }"></image>
			</view>
			<!-- 内容 -->
			<view class="popup-content">
				<view style="margin-top: -50rpx;padding: 10px 14px; border-radius: 14px;height: 100vh;;">
					<view style="display: flex;height: 60px;" @click="changeQQInfo" hover-class="message-hover-class">
						<image mode="aspectFill" :src="_user_info.miniAvatar" :style="{ width: '50px', height: '50px', borderRadius: '50px', marginRight: '16px', marginTop: '5px' }"/>
						<view style="height: 60px;padding-top: 5px;">
							<view style="color: black;font-size: 26rpx;">{{_user_info.nickname}}</view>
							<view style="height: 30rpx;display: flex;" >
								<view class="ichat ichattaiyang" style="margin-right: 6rpx;font-size: 32rpx;"></view>
								<view class="ichat ichatyueliang" style="margin-right: 6rpx;"></view>
								<view class="ichat ichatxingxing" style="margin-right: 6rpx;"></view>
								<view class="ichat ichatxingxing" style="margin-right: 6rpx;"></view>
								<view class="ichat ichatxingxing" style="margin-right: 6rpx;"></view>
							</view>
							<view style="color: #989898;font-size: 20rpx;margin-top: 10rpx;">{{_user_info.signature}}</view>
						</view>
					</view>
					<view @click="show = false" class="iconfont icon-chatguanbi" style="position: absolute;top: 80rpx;right: 60rpx;font-size: 26px;"></view>
					<view style="border-radius: 8px;background-color: white;margin-top: 10px;padding: 1px 10px;height: 100vh;">
						<u-cell-group :border='false'>
							<scroll-view scroll-y style="max-height: 70vh;">
								<u-cell-item :titleStyle="{'fontSize': '30rpx','lineHeight': '70rpx','paddingLeft': '20rpx'}" :border-bottom="false" v-for="(item, index) in groupList" :key="index" :title="item.title" :title-style="{ marginLeft: '20rpx' }" @tap="linkTo(item)">
									<u-icon slot="icon" :class="item.class"></u-icon>
								</u-cell-item>
							</scroll-view>
						</u-cell-group>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 头部 -->
		<view style="height: 180rpx;padding-top: 100rpx;padding-left: 40rpx;padding-right: 40rpx;padding-bottom: 20rpx;">
			<view  style="display: flex;">
				<image mode="aspectFill" @click="show = true" :src="_user_info.miniAvatar" :style="{ width: '36px', height: '36px', borderRadius: '50px', marginRight: '10px', }"/>
				<view style="display: flex;width: 600rpx;justify-content: space-between;">
					<view :style="{ height: '36px', fontSize:'17px',lineHeight: '36px' }">联系人</view>
					<view @click="addFriend" class="iconfont icon-chattianjiahaoyou" style="line-height: 36px;"></view>
				</view>
			</view>
		</view>
        <!-- 搜索和筛选输入 -->
		<u-cell-group :border="false">
			<!-- 搜索框 -->
			<view @click="addFriend">
				<searchInput style="pointer-events:none;" />
				<!-- <u-search shape="square" placeholder="账号/手机号" margin="30rpx" :showAction="false" :disabled="true" style="pointer-events:none;"></u-search> -->
			</view>
			<u-cell-item title="新朋友" @click="goToApply" :border-bottom="false" :title-style="{ color: 'black',fontSize: '16px',height: '36px',lineHeight:'36px' }" :center="true" >
				<u-badge type="error" :is-dot="true" :offset="[36,610]" v-if="hasApply == true"></u-badge>
			</u-cell-item>
			<u-cell-item title="群通知" :border-bottom="false" :title-style="{ color: 'black',fontSize: '16px',height: '36px',lineHeight:'36px' }" :center="true" ></u-cell-item>
		</u-cell-group>
		<view style="height: 20rpx;"></view>

        <!-- 标签页和轮播图 -->
        <view class="tabs-container">
            <u-tabs-swiper ref="tabs" :list="list" :is-scroll="false" count="cate_count" :current="current" @change="tabsChange"/>
            <swiper :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish" class="swiper">
                <swiper-item class="swiper-item" v-for="(tab, index) in list" :key="index">
                    <scroll-view scroll-y class="scroll-view" @scrolltolower="onreachBottom" @scroll="handleScroll" :scroll-into-view="scrollIntoViewId">
						<!-- 这是第一个选项卡的内容 -->
						<view v-if="index === 0">
						    <view class="tab-content">
						        <u-index-list :scrollTop="scrollTop" :index-list="indexList" :active-color="'#3CC51F'" :sticky="false" @click="handleIndexClick">
						            <view v-for="(item, idx) in indexList" :key="idx" v-if="hasFriends(item)">
						                <u-index-anchor :index="item" />
						                <view @longpress="updateRemark(user)" v-for="user in filteredFriends(item)" :key="user.id" class="list-cell" :id="`user-${user.uid}`" @tap="linkToCard(user.friendInfo)" hover-class="message-hover-class">
						                    <image mode="aspectFill" :src="user.friendInfo.miniAvatar" />
						                    <view class="list-cell-name">{{ user.remark ? user.remark : user.friendInfo.nickname }}</view>
						                </view>
						            </view>
						        </u-index-list>
						    </view>
						</view>
						
						<!-- 这是第二个选项卡的内容 -->
						<view v-else-if="index === 1">
							<view class="tab-content">
								<u-collapse :item-style="itemStyle" :head-style="headStyle" :accordion='false' :key="collapseKey">
									<u-collapse-item @longpress="updateGroupName(item)" :title="item.head + '(' + item.body.length + ')'" v-for="(item, index) in friendGroupLists" :key="index" :active-style="activeStyle" :active="activeIndexes.includes(index)" @change="handleCollapseChange(index)">
										<view @longpress="updateRemark(lists)" v-for="(lists, idx) in item.body" :key="idx">
											<u-cell-group>
												<u-cell-item :title-style="titleStyle" :title="lists.remark ? lists.remark : lists.nickname" @click="friendGroupClick(lists)" :label-style="labelStyle" :label="(lists.isOnline == 1 ? '[在线] ' : '[离线] ')+(lists.signature != null ? lists.signature : '')" hover-class="message-hover-class" :arrow='false'>
													<template #icon>
														<image mode="aspectFill" :src="lists.miniAvatar" :style="{ width: '40px', height: '40px', borderRadius: '50px', marginRight: '10px', opacity: lists.isOnline == 1 ? '1' : '0.5' }"/>
													</template>
												</u-cell-item>
											</u-cell-group>
										</view>
									</u-collapse-item>
								</u-collapse>
							</view>
						</view>

						<!-- 这是第三个选项卡的内容 -->
						<view v-else-if="index === 2">
							<view class="tab-content">
								<u-collapse :item-style="itemStyle" :head-style="headStyle" :accordion='false'>
									<u-collapse-item :title="item.head+'('+item.body.length+')'" v-for="(item, index) in chatGroup" :key="index" :active-style="activeStyle">
										<view v-for="(lists, idx) in item.body" :key="idx">
											<u-cell-group>
												<u-cell-item :title-style="titleStyle" :title="lists.groupName" @click="groupClick(lists.id)" :center="true" hover-class="message-hover-class" :arrow='false'>
													<template #icon>
														<image mode="aspectFill" :src="lists.miniAvatar" :style="{ width: '40px', height: '40px', borderRadius: '50px', marginRight: '10px' }"/>
													</template>
												</u-cell-item>
											</u-cell-group>
										</view>
									</u-collapse-item>
								</u-collapse>
							</view>
						</view>
						
						<!-- 这是第四个选项卡的内容 -->
						<view v-else-if="index === 3">
							<view class="tab-content">
								
							</view>
						</view>
						
						<!-- 这是第五个选项卡的内容 -->
						<view v-else-if="index === 4">
							<view class="tab-content">
								
							</view>
						</view>
                        
                    </scroll-view>
                </swiper-item>
            </swiper>
        </view>
		<view>
			<u-modal title="编辑分组名" :titleStyle="{'fontSize': '30rpx','color': 'gray'}" v-model="showUpdateGroupName" @confirm="confirm" ref="uModal" :async-close="true" :show-cancel-button="true">
				<view class="slot-content">
					<u-input v-model="defaultValue"
					maxlength="12"
					type="text" :border="true"
					style="margin:10rpx 20rpx;" />
				</view>
			</u-modal>
		</view>
		<view>
			<u-modal title="更改备注" :titleStyle="{'fontSize': '30rpx','color': 'gray'}" v-model="showUpdateRemark" @confirm="confirmRemark" ref="uModal" :async-close="true" :show-cancel-button="true">
				<view class="slot-content">
					<u-input v-model="defaultRemark"
					maxlength="12"
					type="text" :border="true"
					style="margin:10rpx 20rpx;" />
				</view>
			</u-modal>
		</view>
    </view>
</template>


<script>
import { api } from '../../api/api';
import { myRequest } from '../../util/api';
import searchInput from '@/components/searchInput/index.vue';
import selectInput from '@/components/selectInput/selectInput.vue';

export default {
    components: { searchInput, selectInput },
    data() {
        return {
             list: [
				{ name: '好友' },
				{ name: '分组' },
				{ name: '群聊' },
				{ name: '设备' },
				{ name: '通讯录' },
			],
			groupList: [
				{ title: '我的钱包', class:'iconfont icon-chatqianbao_o', bind:"pages/firendCircle/firendCircle"  },
				{ title: '装扮', class:'iconfont icon-chatgexingzhuangban' },
				{ title: '我的相册', class:'iconfont icon-chatxiangce1' },
				{ title: '我的收藏', class:'iconfont icon-chatwodeshoucang1' },
				{ title: '我的文件', class:'iconfont icon-chatwodewenjian' },
				{ title: '我的钱包', class:'iconfont icon-chatqianbao_o' },
				{ title: '装扮', class:'iconfont icon-chatgexingzhuangban' },
				{ title: '我的相册', class:'iconfont icon-chatxiangce1' },
				{ title: '我的收藏', class:'iconfont icon-chatwodeshoucang1' },
				{ title: '我的文件', class:'iconfont icon-chatwodewenjian' },
			],
			current: 1,
			swiperCurrent: 1,
			scrollTop: 0,
			scrollIntoViewId: '',
            indexList: ['↑','☆', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'],
            selectShow: false,
			itemStyle: {
				padding: '0',
			},
			labelStyle: {
				width: '500rpx',
				whiteSpace: 'nowrap',
				overflow: 'hidden',
				textOverflow: 'ellipsis',
			},
			titleStyle: {
				color: 'black',
				fontSize: '14px',
			},
			headStyle: {
				paddingLeft: '20px'
			},
			activeStyle: {
				color:'#2979ff',
			},
			show: false,
			hasApply: false,
			friendGroupLists: [],
			friend_lists:[],
			activeIndexes: [], // 用于存储当前展开的折叠项索引
			collapseKey: 0, // 用于强制重新渲染 u-collapse 组件
			showUpdateGroupName: false, //修改分组名弹窗
			showUpdateRemark: false, //修改备注弹窗
			contentValue: '',
			defaultValue: '',
			oldGroupName: '',
			defaultRemark: '',
			newRemark: '',
        };
    },
	watch: {
		friendGroupLists: {
			handler(newVal, oldVal) {
				// 重置折叠面板状态
				this.activeIndexes = [];
				// 强制重新渲染 u-collapse 组件
				this.collapseKey += 1;
			},
			deep: true
		}
	},
    methods: {
		handleCollapseChange(index) {
			// 处理折叠项变化的逻辑
			if (this.activeIndexes.includes(index)) {
				this.activeIndexes = this.activeIndexes.filter(i => i !== index);
			} else {
				this.activeIndexes.push(index);
			}
		},
		// 跳转至添加好友页面
		addFriend() {
			uni.navigateTo({
				url: '/pages/addFriend/addFriend'
			});
		},
		changeQQInfo() {
			this.$u.route('pages/qqInfo/qqInfo')
		},
		linkTo(item){
			console.log(item)
			item.bind && this.$u.route(item.bind)
		},
		friendGroupClick(lists) {
			this.$u.route({
				url: 'pages/businessCard/businessCard',
				params: lists
			});
		},
		groupClick(lists) {
			uni.showToast({
				position: 'center',
				title: '暂未开放'
			})
		},
		tabsChange(index) {
			this.swiperCurrent = index;
			this.$nextTick(() => {
				// console.log(`Tab changed to ${index}`);
			});
		},
		transition(e) {
			let dx = e.detail.dx;
			if (this.$refs.tabs) {
				this.$refs.tabs.setDx(dx);
			} else {
				console.error('u-tabs-swiper component is not defined');
			}
		},
		animationfinish(e) {
			let current = e.detail.current;
			if (this.$refs.tabs) {
				this.$refs.tabs.setFinishCurrent(current);
			} else {
				console.error('u-tabs-swiper component is not defined');
			}
			this.swiperCurrent = current;
			this.current = current;
			this.$nextTick(() => {
				// console.log(`Swiper finished at ${current}`);
			});
		},
		linkToCard(lists) {
			this.$u.route({
				url: 'pages/businessCard/businessCard',
				params: lists
			});
		},
		// 跳转至好友申请记录
		goToApply() {
			uni.navigateTo({
				url: '/pages/addFriendHistory/addFriendHistory'
			});
		},
		filteredFriends(pinyin) {
			// return this.friendList.filter(user => user.pinYin === pinYin);
			let friend_lists = this.friend_lists;
			return friend_lists.filter(user => user.pinyin === pinyin);
		},
		hasFriends(pinyin) {
			return this.filteredFriends(pinyin).length > 0;
		},
		showSelect() {
			this.selectShow = !this.selectShow;
		},
		closeSelect() {
			this.selectShow = false;
		},
		onNavigationBarButtonTap({ index }) {
			if (index == 0) {
				this.showSelect();
			}
		},
		handleScroll(event) {
			this.scrollTop = event.detail.scrollTop;
		},
		handleIndexClick(index) {
			// 计算要滚动到的目标元素ID
			const targetId = this.getTargetElementId(index);
			this.scrollIntoViewId = targetId;
		},
		getTargetElementId(index) {
			// 查找第一个匹配的用户ID
			for (const item of this.indexList) {
				if (item === index) {
					const users = this.filteredFriends(item);
					if (users.length > 0) {
						return `user-${users[0].userId}`;
					}
				}
			}
			return '';
		},
		// 确保定义了 onreachBottom 方法
		onreachBottom() {
			console.log('滚动到底部');
			// 在这里实现滚动到底部时需要执行的逻辑
		},

        // 监听返回按钮
        onBackPress() {
            if (this.show) {
                this.show = false;
                return true; // 阻止默认的返回行为
            }
            return false; // 允许默认的返回行为
        },
		// 分组管理
		updateGroupName(item) {
		    uni.vibrateShort({});
			plus.nativeUI.actionSheet({
			    cancel: '取消',
				title: '分组管理“'+item.head+"”",
			    buttons: [
			        { title: '更改分组名' },
			        { title: '分组排序' }
			    ]
			}, function(e) {
			    if (e.index === 1) {
					openUpdateGroup(item.head);
			    } else if (e.index === 2) {
					console.log('分组排序');
			    }
			});
			
			const openUpdateGroup = (title) => {
				this.showUpdateGroupName = true;
				this.defaultValue = title;
				this.oldGroupName = title;
			}
		},
		//更改好友备注
		updateRemark(item) {
			uni.vibrateShort({});
			plus.nativeUI.actionSheet({
			    cancel: '取消',
			    buttons: [
			        { title: '更改备注' },
			    ]
			}, function(e) {
			    if (e.index === 1) {
					openUpdateRemark(item);
			    }
			});
			
			const openUpdateRemark = (item) => {
				this.showUpdateRemark = true;
				this.defaultRemark = item.remark ? item.remark : item.friendInfo.nickname;
				this.friendId = item.fid ? item.fid : item.id;
			}
		},
		async fetchData() {
		  // 异步请求分组数据
		  await myRequest({
		  	url: api.friendGroupList,
		  	method: 'POST',
		  	data: {},
		  	success: (res) => {
		  		if (res.data.code == 200 && res.data.httpCode == 200){
					this.friendGroupLists = res.data.data;
					// 停止下拉刷新
					uni.stopPullDownRefresh();
		  		}
		  	}
		  });
		  // 异步请求好友数据
		  await myRequest({
		  	url: api.userFriends,
		  	method: 'POST',
		  	data: {},
		  	success: (res) => {
		  		if (res.data.code == 200 && res.data.httpCode == 200){
					this.friend_lists = res.data.data;
					// 停止下拉刷新
					uni.stopPullDownRefresh();
		  		}
		  	}
		  });
		},
		//提交修改分组名
		async confirm() {
			let oldGroupName = this.oldGroupName;
			let newGroupName = this.defaultValue;
			await myRequest({
				url: api.updateGroupName,
				data: {
					"old_group_name": oldGroupName,
					"new_group_name": newGroupName
				},
				success: (res) => {
					if (res.data.code == 200 && res.data.httpCode == 200){
						//刷新数据
						this.fetchData();
					} else {
						uni.showToast({
							position: 'center',
							title:"分组名不能包含表情字符"
						})
					}
					//关闭弹窗
					this.showUpdateGroupName = false;
				},
			});
		},
		//提交修改备注
		async confirmRemark() {
			let fid = this.friendId;
			let newRemark = this.defaultRemark;
			await myRequest({
				url: api.updateFriendRemark,
				data: {
					"fid": fid,
					"new_remark": newRemark
				},
				success: (res) => {
					if (res.data.code == 200 && res.data.httpCode == 200){
						//关闭弹窗
						this.showUpdateRemark = false;
						//刷新数据
						this.fetchData();
					}
				},
			});
		},
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	onBackPress() {
		return this.onBackPress();
	},
	async onShow() {
		this.hasApply = false;
		// 好友申请数量
		const response = await myRequest({
			url: api.newFriendNum,
			success: (res) => {
				if (res.data.code == 200 && res.data.httpCode == 200){
					const newFriendNum = res.data.data.newFriendNum;
					if (newFriendNum > 0){
						this.hasApply = true
					} else {
						this.hasApply = false
					}
				}
			}
		});
	},
	async onLoad() {
		this.friendGroupLists = [];
		this.friend_lists = [];
		this.fetchData();
		this.showUpdateGroupName = false;
		//好友分组列表
		const friendGroup = await myRequest({
			url: api.friendGroupList,
			method: 'POST',
			data: {},
			success: (res) => {
				if (res.data.code == 200 && res.data.httpCode == 200){
					var friendGroupLists = res.data.data;
					this.friendGroupLists = friendGroupLists;
				}
			}
		});
		//好友列表
		const friendList = await myRequest({
			url: api.userFriends,
			method: 'POST',
			data: {},
			success: (res) => {
				if (res.data.code == 200 && res.data.httpCode == 200){
					var friend_lists = res.data.data;
					this.friend_lists = friend_lists;
				}
			}
		});
	},
	//下拉刷新
	onPullDownRefresh() {
		// 重新获取数据
		this.fetchData();
	},
};
</script>

<style lang="scss" scoped>
	
	.popup-bgimg {
		height: 400rpx;
		// background-image: url(/static/image/huge.jpg);
		// background-image: url({{_user_info.picture_banner}});
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
	}
	.popup-content {
	  width: 100%; /* 抽屉宽度 */
	  height: 100vh; /* 抽屉高度 */
	  background-color: #f8f8f8; /* 抽屉背景色 */
	  border-radius: 14px;
	}
.content {
    height: 100vh; /* 设置内容区域占满整个视口高度 */
    display: flex;
    flex-direction: column;
	
    .tabs-container {
        flex: 1; /* 让标签页和轮播图容器占据剩余空间 */
        display: flex;
        flex-direction: column;
    }

    .swiper {
        flex: 1; /* 确保 swiper 占据剩余空间 */
        height: 100%; /* 确保 swiper 占据整个容器高度 */
    }

    .swiper-item {
        height: 100%; /* 确保 swiper-item 占据整个容器高度 */
    }

    .scroll-view {
        height: 100%; /* 确保 scroll-view 占据整个容器高度 */
    }

    .list-cell {
        display: flex;
        box-sizing: border-box;
        width: 100%;
        padding: 10px 24rpx;
        overflow: hidden;
        color: #323233;
        font-size: 28rpx;
        line-height: 48rpx;
        background-color: #fff;
        align-items: center;
        
        image {
            width: 76rpx;
            height: 76rpx;
            border-radius: 12rpx;
            flex: 0 0 76rpx;
        }

        &-name {
            padding-left: 20rpx;
        }
    }
}
</style>


